using UnityEngine;
using System.Collections;

public class CameraOrbital : CameraState
{	
	public float m_fOrbitSpeed = 90.0f;
	
	public float m_fMinAngleX = -70.0f;
	public float m_fMaxAngleX = 70.0f;
	public float m_fMinAngleY = -50.0f;
	public float m_fMaxAngleY = 50.0f;
	
	public override Vector3 getRealTargetPosition()
	{
		return sCameras.Instance.m_tTarget.position + sCameras.Instance.getOrbitTransform().TransformDirection(vTargetOffset);
	}
	
	public override Vector3 getRealPosition()
	{
		return sCameras.Instance.m_tTarget.position + sCameras.Instance.getOrbitTransform().TransformDirection(vPositionOffset);
	}
	
	public void orbitCamera()
	{
		Vector3 vDirection = new Vector3(Input.GetAxis("Horizontal2"), Input.GetAxis("Vertical2"), 0.0f);
		
		// check that the camera is inside rotation limits relative to the forward of the target
		float fDegreesToAdd = vDirection.x * m_fOrbitSpeed * Time.deltaTime;
		Vector3 vCameraForward = getRealTargetPosition() - getRealPosition();
		vCameraForward.Normalize();
		vCameraForward.y = 0.0f;
		Vector3 vCharacterForward = sCameras.Instance.m_tTarget.forward;
		vCharacterForward.y = 0.0f;
		float fAngle = MathHelper.getSignedAngle(vCharacterForward, vCameraForward, Vector3.up) * Mathf.Rad2Deg;
		if (fAngle < 0.0f)
		{
			// left
			if (fAngle + fDegreesToAdd < m_fMinAngleX)
			{
				fDegreesToAdd = -fAngle + m_fMinAngleX;
			}
		}
		else
		{
			// right
			if (fAngle + fDegreesToAdd > m_fMaxAngleX)
			{
				fDegreesToAdd = m_fMaxAngleX - fAngle;
			}
		}
		
		Transform tOrbit = sCameras.Instance.getOrbitTransform();
		if (fDegreesToAdd != 0.0f)
		{
			tOrbit.RotateAround(tOrbit.up, fDegreesToAdd * Mathf.Deg2Rad);
		}
		
		vCameraForward = tOrbit.forward;
		vCharacterForward = vCameraForward;
		vCharacterForward.y = 0.0f;
		fDegreesToAdd = vDirection.y * m_fOrbitSpeed * Time.deltaTime;
		fAngle = MathHelper.getSignedAngle(vCharacterForward, vCameraForward, tOrbit.right) * Mathf.Rad2Deg;
		if (fAngle < 0.0f)
		{
			// down
			if (fAngle + fDegreesToAdd < m_fMinAngleY)
			{
				fDegreesToAdd = -fAngle + m_fMinAngleY;
			}
		}
		else
		{
			// top
			if (fAngle + fDegreesToAdd > m_fMaxAngleY)
			{
				fDegreesToAdd = m_fMaxAngleY - fAngle;
			}
		}
		
		if (fDegreesToAdd != 0.0f)
		{
			tOrbit.RotateAround(tOrbit.right, fDegreesToAdd * Mathf.Deg2Rad);
		}
	}
	
	public override void update()
	{
		orbitCamera();
	}
}

